package grade;

import java.sql.*;
import java.util.Properties;

public class DBUtil {

	private static String url;
	private static String user;
	private static String password;
	private static String clsName;

	// 私有构造方法：禁止从外部创建此对象
	private DBUtil() {
	}

	// 静态块代码执行加载驱动
	static {
		Properties p = new Properties();
		try {
			p.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
			clsName = p.getProperty("driver");
			url = p.getProperty("url");
			user = p.getProperty("user");
			password = p.getProperty("password");
			Class.forName(clsName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 获得连接
	public static Connection getConnection() {
		Connection con = null;
		try {
			con = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return con;
	}

	// 释放资源
	public static void close(ResultSet rs) {
		if (rs != null)
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	public static void close(Statement s) {
		if (s != null)
			try {
				s.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	public static void close(Connection con) {
		if (con != null)
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}

	// 通用的CUD操作
	/**
	 * 
	 * @param sql语句
	 * @param 参数
	 * @return 影响的行数
	 */
	public static int executeUpdate(String sql, Object... args) {

		Connection con = DBUtil.getConnection();
		PreparedStatement ps = null;
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(ps);
			close(con);
		}
		return 0;
	}
}
